package com.pallass.admin.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.pallass.admin.domain.SysRole;
import com.pallass.admin.domain.SysUser;
import com.pallass.admin.repository.SysRoleRepository;
import com.pallass.admin.repository.SysUserRepository;
import com.pallass.admin.service.SysUserService;
import com.pallass.common.repository.BaseRepository;
import com.pallass.common.service.BaseServiceImpl;
import com.pallass.utils.PallassConstants;

@Service("userService")
public class SysUserServiceImpl extends BaseServiceImpl<SysUser, Integer> implements SysUserService {

	@Autowired
	private SysUserRepository sysUserDAO;

	@Autowired
	private SysRoleRepository sysRoleDAO;

	public BaseRepository<SysUser, Integer> getBaseDao() {
		return this.sysUserDAO;
	}

	@Override
	public void grant(Integer id, Integer[] roleIds) {
		SysUser user = sysUserDAO.findOne(id);
		Assert.notNull(user, "用户不存在");

		// TODO 是否只允许超级管理员操作

		SysRole role;
		Set<SysRole> roles = new HashSet<>();
		if (roleIds != null) {
			for (Integer rId : roleIds) {
				if (rId == null || rId == 0) {
					continue;
				}
				role = sysRoleDAO.findOne(rId);
				Assert.notNull(role, "角色不存在");
				roles.add(role);
			}
		}
		user.setRoles(roles);
		sysUserDAO.saveAndFlush(user);
	}

	@Override
	public SysUser uniqueUserByUserName(String userName) {
		List<SysUser> users = sysUserDAO.findByUserName(userName);
		if (users == null || users.isEmpty()) {
			return null;
		}
		// FIXME set user name to unique
		return users.get(0);
	}

	@Override
	public void resetpw(Integer id) {
		SysUser user = sysUserDAO.findOne(id);
		user.setPassword(PallassConstants.INITIAL_PASSWORD);
		sysUserDAO.saveAndFlush(user);
	}

}
